<template>
  <div class="multipleUploadImg">
    <div class="img-wrapper">
      <ul class="imgs-list">
        <!-- <li v-for="item in imgs" class="img-item">
          <img :src="item" alt="">
          <div class="del-wrapper">
            <i class="el-icon-delete" @click="delImg(item)"></i>
          </div>
        </li> -->
        <li class="add-btn" @click="uploadHandle">
          <i class="el-icon-plus icon"></i>
        </li>
      </ul>
      <input type="file" ref="inputfile" @change="fileChangeHandle" style="display: none;">
    </div>
  </div>
</template>

<script>
  import * as qiniu from 'qiniu-js'
  import api from '@/api/apiPath'
  import Util from '../../../common/utils'
  export default {
    // name: "upload-img",
    data () {
      return {
        token: '', // 七牛token
        qiniuUrl: '', // 七牛域名，展示图片用
        imgUrl: '', // 图片地址逗号拼接
        imgs: []
      }
    },
    props: ['value'],
    created () {
      this.axios.post(api.UPLOADTOKEN, {}).then(res => {
        this.token = res.data.data.imgToken
        this.qiniuUrl = res.data.data.qiniuUrl
      })
    },
    watch: {
      value (val) {
        this.imgUrl = val
      },
      imgUrl() {
        if (this.imgUrl) {
          this.imgs = this.imgUrl.split(',')
        }
      }
    },
    methods: {
      uploadHandle () {
        const node = this.$refs.inputfile
        node.click()
      },
      fileChangeHandle () {
        const file = this.$refs.inputfile.files[0]
        if (file) {
          // 判断文件类型
          const upType = ['jpg', 'png']
          const fileName = file.name
          const postfix = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length)
          if (upType.indexOf(postfix) === -1) {
            alert('只支持png jpg格式的图片')
            return false
          }
          /**
          // 判断图片宽高
          const fileReader = new FileReader()
          fileReader.readAsDataURL(file)
          const vueThis = this
          fileReader.onloadend = function () {
            const img = new Image()
            img.src = this.result
            img.onload = function () { // 异步的
              if (this.width !== 375 && this.height !== 190) {
                alert('请上传分辨率为 375 * 190 的图片')
              } else {
                vueThis.uploadQiniu(file)
              }
            }
          }
           */
          this.uploadQiniu(file)
        }
      },
      // 用七牛上传
      uploadQiniu (file) {
        const fileName = file.name
        const postfix = fileName.substring(fileName.lastIndexOf('.'), fileName.length)
        const name = Util.getTimeString2(new Date().getTime())
        const token = this.token
        var putExtra = {
          fname: fileName,
          params: {},
          mimeType: null
        }
        var config = {
          useCdnDomain: true
        }
        var observable = qiniu.upload(file, name + postfix, token, putExtra, config)
        const vueThis = this
        observable.subscribe(function (res) {
          console.log('图片上传进度：', res)
        }, function (error) {
          console.error('图片上传失败：', error)
        }, function (res) {
          if (!vueThis.imgUrl) {
            vueThis.imgUrl = `${vueThis.qiniuUrl}${res.key}`
          } else {
            vueThis.imgUrl += `,${vueThis.qiniuUrl}${res.key}`
          }
          vueThis.$emit('uploadSuccess', vueThis.imgUrl)
        })
      },
      delImg (item) {
        const index = this.imgs.indexOf(item)
        if(index != -1) {
          this.imgs.splice(index, 1)
        }
        // 删除了图片重新赋值给父组件
        if (this.imgs.length > 1) {
          this.imgUrl = this.imgs.join(',')
        } else {
          this.imgUrl = this.imgs[0]
        }
        this.$emit('uploadSuccess', this.imgUrl)
        console.log(this.imgUrl)
      }
    }
  }
</script>

<style lang="stylus">
  .multipleUploadImg{
    .img-wrapper{
      .imgs-list{
        display: inline-block;
        min-height: 148px;
        margin: 0;
        padding: 0;
        list-style: none;
        .img-item{
          border: 1px solid #c0ccda;
          border-radius: 6px;
          box-sizing: border-box;
          width: 148px;
          height: 148px;
          float: left;
          margin-right: 5px;
          position: relative;
          overflow: hidden;
          img{
            width: 148px;
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
          }
          .del-wrapper{
            display: none;
            height: 148px;
            background: rgba(0,0,0,0.5)
            position: relative;
            i{
              color: #fff;
              cursor: pointer;
              font-size: 26px;
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
            }
          }
          &:hover{
            .del-wrapper{
              display: block;
            }
          }
        }
        .add-btn{
          float: left;
          background-color: #fbfdff;
          border: 1px dashed #c0ccda;
          border-radius: 6px;
          box-sizing: border-box;
          width: 148px;
          height: 148px;
          cursor: pointer;
          position: relative;
          &:hover{
            border-color: #409eff;
            color: #409eff;
          }
          .icon{
            font-size: 26px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
          }
        }
      }
    }
  }
</style>
